<template>
  <view>
    <view class="items" v-for="(item, index) in contacts" :key="index">
      <view>
        <image :src="item.nicPic" mode="" @click="tocall(item)"></image>
      </view>
      <view>{{ item.nicName }}</view>
	  <label>
	  <text style="font-size: 25rpx;"> {{ischecked?'添加到通讯录':'删除联系人'}}</text>
		  <checkbox :checked="ischecked" @click="check(index)"/>
	  </label>
 
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
	 ischecked:false,
      contacts: [],
      addressBook: []
    };
  },
  onLoad(options) {
	
    try {
      // 解析传递过来的联系人数据
      this.contacts = JSON.parse(decodeURIComponent(options.contacts));
      console.log('解析后的联系人数据:', this.contacts);
      // 获取本地存储的通讯录数据
      this.addressBook = uni.getStorageSync('addressBook') || [];
    } catch (error) {
      console.error('解析联系人数据出错:', error);
    }
  },
  methods: {
    tocall(item) {
      // 传递联系人信息到聊天页面
      uni.navigateTo({
        url: `/pages/publicChat/publicChat?contact=${encodeURIComponent(JSON.stringify(item))}`
      });
    },
    check(index) {
		this.ischecked=!this.ischecked
		if(this.ischecked){
	     if(!this.addressBook.includes(this.contacts[index].userTel)){
			this.addressBook.push(this.contacts[index].userTel); 
		 }
			
		}	
		if(!this.ischecked){
			if(this.addressBook.includes(this.contacts[index].userTel)){
					var idx=this.addressBook.indexOf(this.contacts[index].userTel);
					  this.addressBook.splice(idx,1)
			}
			
		}
      uni.setStorageSync('addressBook', this.addressBook);
      console.log('更新后的通讯录:', this.addressBook);
    }
  }
};
</script>

<style>
.items {
  display: flex;
  flex-direction: column;
  width: 20%;
  margin-left: 50rpx;
 
  align-items: center;
  margin-bottom: 10px;
}

.items image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 10px;
}
</style>